<?php
namespace app\api\controller;


use think\Db;
use app\api\model\Banner as  BannerModel;
use app\api\model\Search  as  SearchModel;
use app\api\model\Mechanism as MechanismModel;
use app\api\model\InstitutionalActivities as InstitutionalActivitiesModel;
use app\api\model\User  as  UserModel;
class Index  extends Base {
    /**
     * 激活绑定设备
     */
    public function bindDevice()
    {
        header("Content-type: text/html; charset=utf-8");
//        $mchid = $_POST['weixin'];
        $mchid = $_POST['mchid'];
        $dev = $_POST['device_info'];
        $res = Db::table('up_shop_device')
            ->where('shop_device_id',$dev)
            ->find();
        if($res){
            $newnew = new \app\api\controller\Weixin();
            $back = $newnew->addFen($mchid);
            if($back['status'] != 200){
                return json_encode(['status'=>0,'msg'=>'请检查商户号正确性']);
            }
            if($res['shop_mchid']){
                if($res['shop_mchid'] == $mchid){
                    Db::table('up_shop_device')->where('shop_device_id',$dev)->update(['shop_status'=>2]);
                    return json_encode(['status'=>200,'msg'=>'激活成功']);
                }else{
                    return json_encode(['status'=>0,'msg'=>'此设备已被其他用户激活，如有疑问请联系相关负责人！']);
                }
            }else{
                $can = Db::table('up_shop_device')
                    ->where('shop_device_id',$dev)
                    ->update(['shop_mchid'=>$mchid,'shop_status'=>2]);
                if($can){
                    return json_encode(['status'=>200,'msg'=>'激活成功']);
                }else{
                    return json_encode(['status'=>0,'msg'=>'激活失败，请重试']);
                }
            }
        }else{
            return json_encode(['status'=>0,'msg'=>'此设备还未录入，请联系相关负责人员']);
        }
    }

    /**
     * 获取轮播图
     * @return string
     */
    public function getBanner()
    {
        $res = Db::table('up_banner')
            ->where('banner_id','>',0)
            ->field('banner_id,banner_title,banner_image')
            ->order('banner_update_time DESC')
            ->page(1,10)
            ->select();
        return json_encode(['status'=>200,'msg'=>$res]);
    }
    /**
     * 获取轮播图详情
     * @return string
     */
    public function getBannerInfo()
    {
        $res = Db::table('up_banner')
            ->where('banner_id',$_POST['banner_id'])
            ->find();
        return json_encode(['status'=>200,'msg'=>$res]);
    }
    /**
     * 获取此设备订单列表
     * order_status:1未完成 2已完成
     *
     * @return string
     */
    public function getOrder()
    {
        if(isset($_POST['page'])){
            $page = $_POST['page'];
        }else{
            $page = 1;
        }
        $res = Db::table('up_order')
            ->where('order_device_id',$_POST['device_info'])
            ->field('order_id,order_num,order_money,order_status,order_time,order_pay_time')
            ->order('order_time DESC')
            ->page($page,20)
            ->select();
        return json_encode(['status'=>200,'msg'=>$res]);
    }


    public function getMyOpenid()
    {
        $appid = config('wechat')['appid'];
        echo "<script> location.href='https://open.weixin.qq.com/connect/oauth2/authorize?appid=$appid&redirect_uri=http://two.xuanwumobile.com/api/Index/getuser&response_type=code&scope=snsapi_userinfo&state=123&connect_redirect=1#wechat_redirect'; </script>";
        exit;
    }
    public function getuser()
    {
        $code = $_REQUEST['code'];
        $appid = config('wechat')['appid'];
        $secret = config('wechat')['secret'];
        $url = "https://api.weixin.qq.com/sns/oauth2/access_token?appid=$appid&secret=$secret&code=$code&grant_type=authorization_code";
        $user = json_decode($this->httpGet($url));
        $openid = $user->openid;
        echo '<span style="font-size: 30px;width: 30%;">您的openid为：<input style="font-size: 30px;width: 70%;text-align:center;padding: 5px;" disabled type="text" name="" value="'.$openid.'"></span>';die;
    }
    public function httpGet($url) {
        $curl = curl_init();
        curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($curl, CURLOPT_TIMEOUT, 500);
        curl_setopt($curl, CURLOPT_URL, $url);
        // 为保证第三方服务器与微信服务器之间数据传输的安全性，所有微信接口采用https方式调用，必须使用下面2行代码打开ssl安全校验。
        // 如果在部署过程中代码在此处验证失败，请到 http://curl.haxx.se/ca/cacert.pem 下载新的证书判别文件。
        curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, FALSE);
        curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, FALSE);
        curl_setopt($curl, CURLOPT_HEADER, FALSE);
        curl_setopt($curl, CURLOPT_RETURNTRANSFER, TRUE);
        $res = curl_exec($curl);
        curl_close($curl);
        return $res;
    }



    public function exportQrcode()
    {
//        $ids = $this->request->param('ids');
//        $ids = explode(',', $ids);
//        $map['device_id'] = ['in', $ids];
//
//        $qrcode = db('device')->where($map)->field('device_id,qrcode')->select()->toArray();
        //这里需要注意该目录是否存在，并且有创建的权限
        $zip_path = ROOT_PATH . 'public' . DS . 'uploads/zip';
        if (!file_exists($zip_path)) {
            mkdir($zip_path);
        }
        $zipname = $zip_path . '/exportdevice_' . date('Y-m-d-H-i-s') . '.zip';

        $zip = new \ZipArchive();
        $res = $zip->open($zipname, \ZipArchive::CREATE);
        if ($res === TRUE) {
            $zip->addFile(ROOT_PATH . 'public' . DS . 'uploads/images/aaa.png', basename(ROOT_PATH . 'public' . DS . 'uploads/images/aaa.png'));
//            foreach ($qrcode as $v) {
//                //这里直接用原文件的名字进行打包，也可以直接命名，需要注意如果文件名字一样会导致后面文件覆盖前面的文件，所以建议重新命名
//                if (!$v['qrcode']) {
//                    continue;
//                }
//                $file = 'upload/' . $v['qrcode'];
//                $new_filename = $v['device_id'] . '.jpg';
//                $zip->addFile($file, $new_filename);
//            }
        }
        $zip->close();
        //这里是下载zip文件
        header("Content-Type: application/zip");
        header("Content-Transfer-Encoding: Binary");

        header("Content-Length: " . filesize($zipname));
        header("Content-Disposition: attachment; filename=\"" . basename($zipname) . "\"");

        readfile($zipname);
        exit;
    }
}